<template>
  <div class="page-container">
    <Position :menu-code="pageCode" :picture="menuInfo.picture" :name="menuInfo.name" class="position"></Position>
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <div class="content-layout">
          <!-- 左侧分类菜单 -->
          <aside class="sidebar">
            <div class="category-section">
              <h3 class="category-title">
                <Icon name="uil:list-ul" size="18" />
                产品分类
              </h3>
              <div class="category-tree">
                <div class="category-item" :class="{ active: !currentCategory }" @click="handleShowAll">
                  <div class="category-content">
                    <Icon name="uil:apps" size="16" />
                    <NuxtLink to="/products">全部产品</NuxtLink>
                  </div>
                </div>
                <template v-for="(category, index) in categoryMenus" :key="category.code">
                  <div
                    v-show="shouldShowCategory(category, index, categoryMenus)"
                    class="category-item"
                    :class="{
                      active: isActiveCategory(category.code),
                      [`level-${category.level}`]: true
                    }"
                    @click="clickCategory(category.code)"
                  >
                    <div class="category-content">
                      <!-- 展开/折叠按钮 -->
                      <button v-if="category.hasChildren" class="expand-btn" @click.stop="toggleCategoryExpand(category.code)">
                        <Icon :name="isCategoryExpanded(category.code) ? 'i-heroicons-chevron-down' : 'i-heroicons-chevron-right'" size="14" />
                      </button>
                      <NuxtLink :to="category.link">{{ category.name }}</NuxtLink>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </aside>
          <!-- 右侧列表 -->
          <main class="products-main">
            <div class="products-container">
              <!-- 产品列表 -->
              <div v-if="pageData.length > 0" class="products-grid">
                <div v-for="(product, index) in pageData" :key="product.id || index" class="product-card" @click="toDetail(product)">
                  <!-- 产品主图 -->
                  <div class="product-image-container">
                    <img v-if="product.mainImages && product.mainImages[0]" :src="product.mainImages[0]" :alt="product.title" class="product-image" loading="lazy" />
                    <div v-else class="product-image-placeholder">
                      <Icon name="uil:image" size="48" />
                    </div>
                  </div>

                  <!-- 产品信息 -->
                  <div class="product-info">
                    <h3 class="product-title">{{ product.title }}</h3>
                    <p class="product-description">{{ product.subtitle }}</p>
                  </div>
                </div>
              </div>

              <!-- 空状态 -->
              <div v-else class="empty-state">
                <Icon name="uil:box" size="64" />
                <p>暂无产品数据</p>
              </div>

              <!-- 翻页组件 -->
              <div v-if="totalPages > 1" class="pagination">
                <button class="pagination-btn" :class="{ disabled: currentPage === 1 }" @click="goToPage(1)" :disabled="currentPage === 1">首页</button>
                <button class="pagination-btn" :class="{ disabled: currentPage === 1 }" @click="goToPage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
                <span class="pagination-info"> 第 {{ currentPage }} 页 / 共 {{ totalPages }} 页 </span>
                <button class="pagination-btn" :class="{ disabled: totalPages <= pageData.length }" @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
              </div>
            </div>
          </main>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getListDetailAll } from "@/api/projects";
import { mockProjectPage } from "@/assets/mock";
import Position from "~/components/Position.vue";
const props = defineProps({
  pageType: {
    type: String,
    default: "page"
  },
  basePageCode: {
    type: String,
    default: ""
  }
});
const router = useRouter();
/**
 * 动态页面代码，根据当前分类参数切换
 * @returns 当前页面代码
 */
const pageCode = computed(() => {
  // 如果currentCategory为空，返回基础pageCode
  if (!currentCategory.value) {
    return props.basePageCode;
  }
  // 根据currentCategory返回对应的分类code
  return currentCategory.value;
});
const pageData = ref<any>([]);
const menuInfo = ref<any>({});
const route = useRoute();
const appConfig = useAppConfig();
const { menus } = appConfig.systemConfig;
// console.log("all:", route.params.all); // array

// 当前选中的分类
const currentCategory = ref("");

// 折叠状态管理
const expandedCategories = ref<Set<string>>(new Set());

// 分页状态管理
const currentPage = ref(1);
const pageSize = ref(12); // 每页显示12个产品
const totalPages = ref(0); // 总页数

/**
 * 递归构建分类菜单树形结构
 * @param menuList - 菜单列表数组
 * @param level - 当前层级（用于样式区分）
 * @returns 带层级信息的分类菜单数组
 */
const buildCategoryTree = (menuList: any[], level: number = 0): any[] => {
  const categories: any[] = [];

  if (!menuList || !Array.isArray(menuList)) {
    return categories;
  }

  for (const menu of menuList) {
    // 如果当前菜单是分类类型，添加到结果中
    if (menu.modelType === "category") {
      const categoryItem = {
        ...menu,
        level, // 添加层级信息
        hasChildren: menu.children && Array.isArray(menu.children) && menu.children.length > 0
      };
      categories.push(categoryItem);

      // 如果有子菜单，递归处理
      if (categoryItem.hasChildren) {
        const childCategories = buildCategoryTree(menu.children, level + 1);
        categories.push(...childCategories);
      }
    }
  }

  return categories;
};

/**
 * 获取分类菜单列表
 * 递归构建带层级信息的分类菜单树
 */
const categoryMenus = computed(() => {
  if (!menuInfo.value.children || !Array.isArray(menuInfo.value.children)) {
    return [];
  }
  return buildCategoryTree(menuInfo.value.children);
});

/**
 * 切换分类展开/折叠状态
 * @param categoryCode - 分类代码
 */
const toggleCategoryExpand = (categoryCode: string) => {
  if (expandedCategories.value.has(categoryCode)) {
    expandedCategories.value.delete(categoryCode);
  } else {
    expandedCategories.value.add(categoryCode);
  }
};

/**
 * 检查分类是否展开
 * @param categoryCode - 分类代码
 * @returns 是否展开
 */
const isCategoryExpanded = (categoryCode: string): boolean => {
  return expandedCategories.value.has(categoryCode);
};

/**
 * 查找父级分类代码
 * @param categoryCode 目标分类代码
 * @param categories 分类列表
 * @returns 父级分类代码数组
 */
const findParentCategories = (categoryCode: string, categories: any[]): string[] => {
  const parents: string[] = [];

  const targetIndex = categories.findIndex((cat) => cat.code === categoryCode);
  if (targetIndex === -1) return parents;

  const targetCategory = categories[targetIndex];
  const targetLevel = targetCategory.level;

  // 向前查找所有父级分类
  for (let i = targetIndex - 1; i >= 0; i--) {
    const category = categories[i];
    if (category.level < targetLevel) {
      parents.unshift(category.code);
      if (category.level === 0) break; // 到达顶级分类
    }
  }

  return parents;
};

/**
 * 自动展开指定分类及其所有父级分类
 * @param categoryCode - 需要展开的分类代码
 */
const expandCategoryAndParents = (categoryCode: string) => {
  const categories = categoryMenus.value;
  if (!categories || categories.length === 0) return;

  // 查找所有父级分类
  const parentCodes = findParentCategories(categoryCode, categories);

  // 展开所有父级分类
  parentCodes.forEach((parentCode) => {
    expandedCategories.value.add(parentCode);
  });

  // 如果目标分类有子分类，也展开它
  const targetCategory = categories.find((cat) => cat.code === categoryCode);
  if (targetCategory && targetCategory.hasChildren) {
    expandedCategories.value.add(categoryCode);
  }
};

/**
 * 检查分类是否应该显示
 * @param category - 分类对象
 * @param index - 当前索引
 * @param categories - 所有分类数组
 * @returns 是否显示
 */
const shouldShowCategory = (category: any, index: number, categories: any[]): boolean => {
  // 顶级分类始终显示
  if (category.level === 0) {
    return true;
  }

  // 查找父级分类
  for (let i = index - 1; i >= 0; i--) {
    const prevCategory = categories[i];
    if (prevCategory.level === category.level - 1) {
      return isCategoryExpanded(prevCategory.code);
    }
  }

  return false;
};

/**
 * 检查分类是否为当前激活状态
 * @param categoryCode - 分类代码
 * @returns 是否激活
 */
const isActiveCategory = (categoryCode: string): boolean => {
  return currentCategory.value === categoryCode;
};

/**
 * 分类点击事件处理
 * @param categoryId - 分类ID
 */
const clickCategory = (categoryId: string) => {
  // 分类点击事件处理
  currentCategory.value = categoryId;
  currentPage.value = 1;
  expandCategoryAndParents(categoryId);
  getPageData();
};
/**
 * 获取页面数据
 */
const getPageData = async () => {
  currentPage.value = 1; // 重置页码
  try {
    if (menuInfo.value.modelId) {
      const res = await getListDetailAll({
        moduleId: menuInfo.value.modelId,
        categoryId: currentCategory.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
      if (Array.isArray(res.rows)) {
        pageData.value = res.rows;
        totalPages.value = res.total;
      }
      console.log(res.rows, "页面数据");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

/**
 * 翻页处理
 */
const goToPage = (pageNum: number) => {
  if (pageNum < 1 || pageNum > totalPages.value) return;
  currentPage.value = pageNum;
  getPageData();
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: "smooth" });
};

/**
 * 显示全部产品
 */
const handleShowAll = async () => {
  currentCategory.value = "";
  currentPage.value = 1;
  try {
    if (menuInfo.value.modelId) {
      const res = await getListDetailAll({
        moduleId: menuInfo.value.modelId,
        categoryId: ""
      });
      pageData.value = res.rows;
      totalPages.value = res.total;
    }
  } catch (error) {
    console.error("获取全部数据失败:", error);
  }
};

/**
 * 根据code在menus数组中递归查找菜单信息
 */
// function findMenuByCode(menuList: any[], targetCode: string): any | null {
//   for (const menu of menuList) {
//     if (menu.code === targetCode) return menu;
//     if (menu.children?.length > 0) {
//       const result = findMenuByCode(menu.children, targetCode);
//       if (result) return result;
//     }
//   }
//   return null;
// }

/**
 * 根据link关键字在menus数组中递归查找菜单信息
 */
const findMenuByLink = (menuList: any[], targetLink: string): any | null => {
  for (const menu of menuList) {
    if (menu.link.includes(targetLink)) return menu;
    if (menu.children?.length > 0) {
      const result = findMenuByLink(menu.children, targetLink);
      if (result) return result;
    }
  }
  return null;
};

const toDetail = (product: any) => {
  router.push(product.link);
};

/**
 * 初始化页面数据
 */
const initPage = async () => {
  try {
    if (!props.pageType.includes("$")) {
      const menuInfoRes = useFindMenuByCode(menus, props.basePageCode);
      if (menuInfoRes) {
        menuInfo.value = menuInfoRes;
        useHead({
          title: menuInfoRes.name,
          meta: [
            { name: "keywords", content: menuInfoRes.keywords },
            { name: "description", content: menuInfoRes.description }
          ]
        });

        const newParams = route.params.all;
        if (newParams && Array.isArray(newParams) && newParams.length > 0) {
          const paramsKey = newParams[0] as string;
          const category = findMenuByLink(menus, paramsKey);
          if (category) {
            currentCategory.value = category.code;
            nextTick(() => {
              expandCategoryAndParents(category.code);
            });
          }
        } else {
          currentCategory.value = "";
        }

        if (menuInfoRes.modelId) {
          getPageData();
        }
      }
    } else {
      pageData.value = mockProjectPage;
    }
  } catch (error) {
    console.error("页面初始化失败:", error);
  }
};

// 初始化页面
initPage();
</script>

<style scoped lang="scss">
/* 产品页面主容器 */
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, $custom-primary 0%, var(--custom-secondary) 100%);
  color: white;
  padding: 3rem 0 2rem;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-description {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

/* 主要内容布局 */
.main-content {
  padding: 20px 0;
  .container {
    max-width: 1400px;
    margin: 0 auto;
  }
}

.content-layout {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 2rem;
  align-items: start;
}

/* 左侧边栏 */
.sidebar {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: sticky;
  top: 2rem;
  min-height: 600px;
}

.category-section {
  padding: 1.5rem;
}

.category-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.1rem;
  font-weight: 600;
  color: $custom-primary;
  margin-bottom: 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 2px solid #e2e8f0;
}

.category-tree {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.category-item {
  padding: 0.75rem 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: #f1f5f9;
    border-color: $custom-primary;
    transform: translateX(4px);
  }

  &.active {
    background: linear-gradient(135deg, $custom-primary, #e6cfb6);
    color: white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  /* 层级样式 */
  &.level-0 {
    margin-left: 0;
    .category-content {
      padding: 0 1rem;
      font-size: 14px;
    }
  }

  &.level-1 {
    margin-left: 18px;
    .category-content {
      padding: 2px 0;
      font-size: 0.9rem;
      color: #64748b;
    }
    &.active .category-content {
      color: white;
    }
  }

  &.level-2 {
    margin-left: 24px;
    .category-content {
      padding: 0.375rem 0.75rem;
      font-size: 0.8rem;
      color: #94a3b8;
    }
    &.active .category-content {
      color: white;
    }
  }

  &.level-3 {
    margin-left: 3rem;
    .category-content {
      padding: 0.375rem 0.75rem;
      font-size: 0.8rem;
      color: #94a3b8;
    }
    &.active .category-content {
      color: white;
    }
  }
}

.category-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 500;
  width: 100%;
  transition: all 0.2s ease;
}

.category-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.expand-btn {
  padding: 0;
  background: transparent;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 16px;
  height: 16px;

  &:hover {
    opacity: 0.7;
  }
}

.category-count {
  background: rgba(255, 255, 255, 0.2);
  color: inherit;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
}

.category-item:not(.active) .category-count {
  background: $custom-primary;
  color: white;
}

/* 右侧产品展示区域 */
.products-main {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 600px;
}

.products-container {
  padding: 2rem;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

/* 产品卡片 */
.product-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #e2e8f0;
  cursor: pointer;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
    border-color: $custom-primary;

    .product-image {
      transform: scale(1.05);
    }
  }
}

/* 产品图片容器 */
.product-image-container {
  position: relative;
  height: 200px;
  overflow: hidden;
  background: #f8fafc;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #94a3b8;
  background: #f1f5f9;
}

/* 产品信息 */
.product-info {
  padding: 1.5rem;
}

.product-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.75rem;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-description {
  font-size: 0.9rem;
  color: #64748b;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  color: #94a3b8;
  text-align: center;

  p {
    margin-top: 1rem;
    font-size: 14px;
  }
}

/* 翻页组件 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 2rem 0;
  border-top: 1px solid #e2e8f0;
  margin-top: 2rem;
}

.pagination-btn {
  padding: 4px 12px;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 2px;
  color: #374151;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;

  &:hover:not(.disabled) {
    background: $custom-primary;
    color: white;
    border-color: $custom-primary;
    transform: translateY(-1px);
  }

  &.disabled {
    background: #f9fafb;
    color: #9ca3af;
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.pagination-info {
  padding: 4px 12px;
  color: #6b7280;
  font-weight: 500;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-layout {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }

  .sidebar {
    position: static;
    order: 2;
  }

  .products-main {
    order: 1;
  }

  .category-tree {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 0.5rem;
  }
}

@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
  }

  .products-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
    padding: 1.5rem;
  }

  .category-tree {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 640px) {
  .page-header {
    padding: 2rem 0 1.5rem;
  }

  .page-title {
    font-size: 1.75rem;
  }

  .products-grid {
    padding: 1rem;
  }

  .product-info {
    padding: 1rem;
  }

  .category-section {
    padding: 1rem;
  }
}
</style>
